package com.seanchenxi.gwt.xmlrpc.client.util;

import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;

/**
 * The Class XmlParser.
 */
public class XmlParser {

	/**
	 * Text value of.
	 *
	 * @param node the node
	 * @return the string
	 */
	public static String textValueOf(Node node) {
		if(node == null) return null;
		if(node.getChildNodes() == null) return null;
		
		if (node.getChildNodes().getLength() != 1)
			return null;

		Node textNode = node.getFirstChild();

		if (!isText(textNode))
			return null;

		return textNode.getNodeValue();
	}

	/**
	 * First element child.
	 *
	 * @param parentNode the parent node
	 * @return the element
	 */
	public static Element firstElementChild(Node parentNode) {
		if(parentNode == null) return null;
		NodeList nodeList = parentNode.getChildNodes();
		if (nodeList != null)
			for (int i = 0; i < nodeList.getLength(); i++) {
				if (isElement(nodeList.item(i)))
					return (Element) nodeList.item(i);
			}
		return null;
	}

	/**
	 * Element child count.
	 *
	 * @param nodeList the node list
	 * @return the int
	 */
	public static int elementChildCount(NodeList nodeList) {
		int nbEl = 0;
		if (nodeList != null)
			for (int i = 0; i < nodeList.getLength(); i++) {
				if (isElement(nodeList.item(i)))
					nbEl++;
			}
		return nbEl;
	}

	/**
	 * Checks for element child.
	 *
	 * @param parentNode the parent node
	 * @return true, if successful
	 */
	public static boolean hasElementChild(Node parentNode) {
		return (firstElementChild(parentNode) != null);
	}

	/**
	 * Checks if is element.
	 *
	 * @param node the node
	 * @return true, if is element
	 */
	public static boolean isElement(Node node) {
		if (node == null)
			return false;
		return Node.ELEMENT_NODE == node.getNodeType();
	}

	/**
	 * Checks if is text.
	 *
	 * @param node the node
	 * @return true, if is text
	 */
	public static boolean isText(Node node) {
		if (node == null)
			return false;
		return Node.TEXT_NODE == node.getNodeType();
	}

	/**
	 * Checks if is equal.
	 *
	 * @param node the node
	 * @param tagName the tag name
	 * @return true, if is equal
	 */
	public static boolean isEqual(Node node, String tagName) {
		if (node != null && tagName!=null)
			return tagName.equals(node.getNodeName());
		return false;
	}
	
}
